package UDPSIDE;

import java.io.IOException;
import java.net.*;

/**
 * @创建人 MBY381
 * @创建时间 2022/6/7 14:16
 * @描述 暂无
 */
public class UDPClientThread implements Runnable {
    private final DatagramSocket socket;
    private final Integer senderPort;
    private final InetAddress address;

    public UDPClientThread(String address, Integer port) throws SocketException, UnknownHostException {
        this.address = InetAddress.getByName(address);
        this.senderPort = port;
        this.socket = new DatagramSocket(port);
    }


    @Override
    public void run() {
        System.out.println("UDPReceiveThread启动");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            this.send("mby", "123456");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public String send(String id, String password) throws IOException {
        byte[] content = (id + "." + password).getBytes();
        DatagramPacket packet = new DatagramPacket(content, content.length, address, 9999);
        try {
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[1024];
        DatagramPacket answerPacket = new DatagramPacket(buffer, buffer.length);
        socket.receive(answerPacket);
        byte[] data = answerPacket.getData();
        return new String(data, 0, data.length);
    }

    public void close() {
        socket.close();
    }

    public static void main(String[] args) throws IOException {
        UDPClientThread udpSenderThread = new UDPClientThread("192.168.13.249", 8887);
        String answer = udpSenderThread.send("mby", "123456").trim();
        System.out.println("UDP测试结果：" + answer.equals("true"));
    }
}
